"use strict";
const Pkg = require("@hjc-cli-dev/package");
const log = require("@hjc-cli-dev/log");
const path = require("path");
const { exec: spawn } = require("@hjc-cli-dev/utils");
const settings = {
    init: "@hjc-cli-dev/init",
};
const CACHE_DIR = "dependencies";
async function exec() {
    const cmdObj = arguments[arguments.length - 1];
    const cmdName = cmdObj.name();
    let storeDir = "";
    let pkg;
    let targetPath = process.env.CLI_TARGET_PATH; //用户指定的安装目录
    const homePath = process.env.CLI_HOME_PATH;
    const packageName = settings[cmdName];
    const packageVersion = "latest";

    log.verbose("targetPath", targetPath);
    log.verbose("homePath", homePath);
    if (!targetPath) {
        targetPath = path.resolve(homePath, CACHE_DIR); //用户未指定pkg安装目录则使用用户主目录
        storeDir = path.resolve(targetPath, "node_modules"); //用户node_modules包缓存目录
        log.verbose("targetPath", targetPath);
        log.verbose("storeDir", storeDir);
        pkg = new Pkg({
            targetPath,
            storeDir,
            packageName,
            packageVersion,
        });

        if (await pkg.exists()) {
            // 更新pkg
            await pkg.update();
        } else {
            // 安装pkg
            await pkg.install();
        }
    } else {
        //指定了安装目录
        pkg = new Pkg({
            targetPath,
            packageName,
            packageVersion,
        });
    }
    const rootFile = pkg.getRootFilePath();
    if (rootFile) {
        try {
            // 处理参数
            const args = Array.from(arguments);
            const cmd = args[args.length - 1];
            const o = Object.create(null);
            Object.keys(cmd).forEach((ele) => {
                if (cmd.hasOwnProperty(ele) && !ele.startsWith("_") && ele !== "parent") {
                    o[ele] = cmd[ele];
                }
            });
            args[args.length - 1] = o;
            const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`;
            // 生成node多进程动态执行代码;
            const child = spawn("node", ["-e", code], {
                cwd: process.cwd(), //执行当前位置的包
                stdio: "inherit", //控制台流式输出信息
            });
            child.on("error", (e) => {
                //监听子进程错误
                log.error(e.message);
                process.emit(1); //返回错误信息
            });
            child.on("exit", (e) => {
                //监听子进程完成
                log.verbose("命令执行成功！" + e);
                process.emit(e); //返回正确信息
            });
        } catch (error) {
            log.error(error.message);
        }
    }
}

module.exports = exec;
